import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_decoration.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_shadow.dart';
import 'package:kq_flutter_pad_widgets/resources/kq_pad_theme_colors.dart';
import 'package:kq_flutter_pad_widgets/theme/kq_theme_manager.dart';
import 'package:kq_flutter_pad_widgets/widgets/tabbar/kq_tab_bar.dart';

/// 带阴影TabBar控件
class KqPadShadowTabBar extends StatefulWidget {
  /// tab 数据
  final List<PadTabDataEntity> tabs;

  /// 选中下标
  final int index;

  /// tab选中
  final Function(int index)? onTap;

  /// 自定义按钮padding
  final EdgeInsets? btnPadding;

  /// 自定义按钮最小宽度
  final double? btnMinWidth;

  /// 外围是否展示 boxShadow
  final bool showShadow;

  const KqPadShadowTabBar({
    Key? key,
    required this.tabs,
    this.index = 0,
    this.onTap,
    this.btnPadding,
    this.btnMinWidth,
    this.showShadow = true,
  }) : super(key: key);

  @override
  KqPadShadowTabBarState createState() => KqPadShadowTabBarState();
}

class KqPadShadowTabBarState extends State<KqPadShadowTabBar> {
  var scrollController = ScrollController();

  var scrollKey = GlobalKey();

  List<GlobalKey> textKeys = [];

  var lastIndex = 0;

  /// 滚动到指定位置
  void scrollToIndex() {
    if (scrollController.hasClients) {
      var maxX = scrollController.position.maxScrollExtent;
      double offset = scrollController.offset.toDouble();
      if (maxX == 0) {
        // 不能滚动，不用管
        return;
      }

      final RenderBox? overlay =
          scrollKey.currentContext?.findRenderObject() as RenderBox?;
      double scrollViewWidth = overlay?.size.width ?? 0;
      if (scrollViewWidth == 0) {
        return;
      }

      double lastTabLeft = getLastTabLeft();
      if (widget.index < lastIndex && lastTabLeft - offset < 0) {
        // 超出左边了，需要右滚动
        double distance = lastTabLeft - offset;
        scrollController.animateTo(offset + distance,
            duration: const Duration(milliseconds: 350), curve: Curves.easeIn);
      } else if (widget.index > lastIndex) {
        double nextTabRight = getNextTabRight();
        if (nextTabRight - offset > scrollViewWidth) {
          // 超出右边了，需要左滚动
          double distance = (nextTabRight - offset) - scrollViewWidth;
          scrollController.animateTo(offset + distance,
              duration: const Duration(milliseconds: 350),
              curve: Curves.easeIn);
        }
      }
    }
    lastIndex = widget.index;
  }

  double? getWidgetWidth(GlobalKey globalKey) {
    final RenderBox? overlay =
        globalKey.currentContext?.findRenderObject() as RenderBox?;
    return overlay?.size.width;
  }

  double getLastTabLeft() {
    //如果上一个tab的左边没显示出来，滚动到上一个
    double tabLeft = 0;
    if (widget.index == 0 || widget.index == 1) {
      return 0;
    }
    // 上一个的左边就是上上个的右边
    int lastLastIndex = widget.index - 2;
    for (int i = 0; i <= (lastLastIndex); i++) {
      double textWidth = getWidgetWidth(textKeys[i]) ?? 0;
      tabLeft += (textWidth);
    }
    return tabLeft;
  }

  double getNextTabRight() {
    //如果下一个tab的右边没有显示出来，滚动到下一个的右边
    double tabRight = 0;
    int nextIndex = (widget.tabs.length - 1) > widget.index
        ? widget.index + 1
        : widget.index;
    for (int i = 0; i <= (nextIndex); i++) {
      double textWidth = getWidgetWidth(textKeys[i]) ?? 0;
      tabRight += (textWidth);
    }
    return tabRight;
  }

  @override
  void initState() {
    lastIndex = widget.index;
    super.initState();
  }

  @override
  void didUpdateWidget(covariant KqPadShadowTabBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.index != widget.index) {
      scrollToIndex();
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> tabs = [];

    textKeys.clear();
    for (int i = 0; i < (widget.tabs.length); i++) {
      var textGlobalKey = GlobalKey();
      textKeys.add(textGlobalKey);
      var tab = widget.tabs[i];
      tabs.add(InkWell(
        key: textGlobalKey,
        onTap: () {
          widget.onTap?.call(i);
        },
        splashColor: Colors.transparent,
        hoverColor: Colors.transparent,
        highlightColor: Colors.transparent,
        child: Container(
          decoration: i == widget.index
              ? KqBoxDecoration(
                  color: KqPadThemeManager.instance
                          .getConfig()
                          .commonConfig
                          .mainColor ??
                      KqPadThemeColors.db46,
                  borderRadius: BorderRadius.all(Radius.circular(200.dm)),
                  boxShadow: [
                      KqBoxShadow(
                          offset: Offset(0, 1.dm),
                          blurRadius: 2.dm,
                          spreadRadius: 0,
                          color: Colors.black.withOpacity(0.15),
                          inset: false)
                    ])
              : null,
          constraints: BoxConstraints(
            minWidth: widget.btnMinWidth ?? 44.dm,
          ),
          alignment: Alignment.center,
          padding: widget.btnPadding ??
              EdgeInsets.symmetric(horizontal: 8.dm, vertical: 7.dm),
          child: Text(
            i == widget.index ? (tab.selectedTitle ?? tab.title) : tab.title,
            style: TextStyle(
                color: i == widget.index
                    ? KqPadThemeColors.textWhite
                    : KqPadThemeColors.text26,
                height: 1,
                fontSize: 7.dm),
          ),
        ),
      ));
    }

    if (widget.tabs.isEmpty) {
      return Container();
    }

    return Container(
      clipBehavior: Clip.none,
      decoration: KqBoxDecoration(
          color: KqPadThemeColors.tabBarBgColor,
          borderRadius: BorderRadius.all(Radius.circular(200.dm)),
          boxShadow: widget.showShadow
              ? [
                  KqBoxShadow(
                      offset: Offset(1.dm, 1.dm),
                      blurRadius: 2.dm,
                      spreadRadius: 0,
                      color: KqPadThemeColors.shadowColor3,
                      inset: true),
                  KqBoxShadow(
                      offset: Offset(-1.dm, -1.dm),
                      blurRadius: 3.dm,
                      spreadRadius: 0,
                      color: KqPadThemeColors.textWhite,
                      inset: true)
                ]
              : null),
      padding: EdgeInsets.symmetric(horizontal: 3.dm),
      child: ScrollConfiguration(
        behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(200.dm)),
          child: SingleChildScrollView(
            key: scrollKey,
            scrollDirection: Axis.horizontal,
            controller: scrollController,
            clipBehavior: Clip.none,
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 3.dm),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: tabs,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
